package com.primforce.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author tangjiakai
 * @Date 2024/12/10 10:32
 * @Description: TODO
 */
public class RedisServiceImpl implements RedisService{


    @Resource
    RedisTemplate redisTemplate;


    @Override
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Set<String> getPattrenKeysSet(String pattren) {
        Set<String> keySet = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keysTemp = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(pattren).count(10000).build());
            while (cursor.hasNext()) {
                keysTemp.add(new String(cursor.next()));
            }
            return keysTemp;
        });
        return keySet;
    }
}